<?php
/*
//backup.php
This is Total backup.
Before we install - we make an array with filenames and backup them.
So they don't have any changes and don't rewrites if we make changes in file several times.
*/

function sql_backup(){
        global $contrib;
        ($contrib) ? $cip=$contrib: $cip=$_GET['contrib'];
        tep_set_time_limit(0);
        //$backup_file=$cip.'-'.date('YmdHis').'.sql';
        $backup_file=$cip.'.sql';

        // From original admin/backup.php:
        $fp = fopen(DIR_FS_BACKUP . $backup_file, 'w');

        $schema = '# osCommerce, Open Source E-Commerce Solutions' . "\n" .
                  '# http://www.oscommerce.com' . "\n" .
                  '#' . "\n" .
                  '# Database Backup For ' . STORE_NAME . "\n" .
                  '# Copyright (c) ' . date('Y') . ' ' . STORE_OWNER . "\n" .
                  '#' . "\n" .
                  '# Database: ' . DB_DATABASE . "\n" .
                  '# Database Server: ' . DB_SERVER . "\n" .
                  '#' . "\n" .
                  '# Backup Date: ' . date(PHP_DATE_TIME_FORMAT) . "\n\n";
        fputs($fp, $schema);

        $tables_query = tep_db_query('show tables');
        while ($tables = tep_db_fetch_array($tables_query)) {
          list(,$table) = each($tables);

          $schema = 'drop table if exists ' . $table . ';' . "\n" .
                    'create table ' . $table . ' (' . "\n";

          $table_list = array();
          $fields_query = tep_db_query("show fields from " . $table);
          while ($fields = tep_db_fetch_array($fields_query)) {
            $table_list[] = $fields['Field'];

            $schema .= '  ' . $fields['Field'] . ' ' . $fields['Type'];

            if (strlen($fields['Default']) > 0) $schema .= ' default \'' . $fields['Default'] . '\'';

            if ($fields['Null'] != 'YES') $schema .= ' not null';

            if (isset($fields['Extra'])) $schema .= ' ' . $fields['Extra'];

            $schema .= ',' . "\n";
          }

          $schema = ereg_replace(",\n$", '', $schema);

// add the keys
          $index = array();
          $keys_query = tep_db_query("show keys from " . $table);
          while ($keys = tep_db_fetch_array($keys_query)) {
            $kname = $keys['Key_name'];

            if (!isset($index[$kname])) {
              $index[$kname] = array('unique' => !$keys['Non_unique'],
                                     'columns' => array());
            }

            $index[$kname]['columns'][] = $keys['Column_name'];
          }

          while (list($kname, $info) = each($index)) {
            $schema .= ',' . "\n";

            $columns = implode($info['columns'], ', ');

            if ($kname == 'PRIMARY') {
              $schema .= '  PRIMARY KEY (' . $columns . ')';
            } elseif ($info['unique']) {
              $schema .= '  UNIQUE ' . $kname . ' (' . $columns . ')';
            } else {
              $schema .= '  KEY ' . $kname . ' (' . $columns . ')';
            }
          }

          $schema .= "\n" . ');' . "\n\n";
          fputs($fp, $schema);

// dump the data
          $rows_query = tep_db_query("sElect " . implode(',', $table_list) . " from " . $table);
          while ($rows = tep_db_fetch_array($rows_query)) {
            $schema = 'insert into ' . $table . ' (' . implode(', ', $table_list) . ') values (';

            reset($table_list);
            while (list(,$i) = each($table_list)) {
              if (!isset($rows[$i])) {
                $schema .= 'NULL, ';
              } elseif (tep_not_null($rows[$i])) {
                $row = addslashes($rows[$i]);
                $row = ereg_replace("\n#", "\n".'\#', $row);

                $schema .= '\'' . $row . '\', ';
              } else {
                $schema .= '\'\', ';
              }
            }

            $schema = ereg_replace(', $', '', $schema) . ');' . "\n";
            fputs($fp, $schema);

          }
        }

        fclose($fp);

/* Vlad
        if (isset($HTTP_POST_VARS['download']) && ($HTTP_POST_VARS['download'] == 'yes')) {
          switch ($HTTP_POST_VARS['compress']) {
            case 'gzip':
              exec(LOCAL_EXE_GZIP . ' ' . DIR_FS_BACKUP . $backup_file);
              $backup_file .= '.gz';
              break;
            case 'zip':
              exec(LOCAL_EXE_ZIP . ' -j ' . DIR_FS_BACKUP . $backup_file . '.zip ' . DIR_FS_BACKUP . $backup_file);
              unlink(DIR_FS_BACKUP . $backup_file);
              $backup_file .= '.zip';
          }
          header('Content-type: application/x-octet-stream');
          header('Content-disposition: attachment; filename=' . $backup_file);

          readfile(DIR_FS_BACKUP . $backup_file);
          unlink(DIR_FS_BACKUP . $backup_file);

          exit;
        } else {
          switch ($HTTP_POST_VARS['compress']) {
            case 'gzip':
*/
              exec(LOCAL_EXE_GZIP . ' ' . DIR_FS_BACKUP . $backup_file);
/* Vlad
              break;
            case 'zip':
              exec(LOCAL_EXE_ZIP . ' -j ' . DIR_FS_BACKUP . $backup_file . '.zip ' . DIR_FS_BACKUP . $backup_file);
              unlink(DIR_FS_BACKUP . $backup_file);
          }

          $messageStack->add_session(SUCCESS_DATABASE_SAVED, 'success');
        }
*/



}


function backup_all_files($files=array()) {
    global $contrib;
    ($contrib) ? $cip=$contrib: $cip=$_GET['contrib'];
    if (count($files)>0) {
        foreach ($files as $filepath)    backup_file($filepath, $cip);
        return count($files)." files to ".DIR_FS_BACKUP.$cip.'/';
    } else     return "nothing.";

}

function backup_file($filepath, $cip){
    if ($cip && $filepath && is_file(DIR_FS_CATALOG.$filepath)){
        if(!is_dir(DIR_FS_BACKUP.$cip))     if(!@mkdir(DIR_FS_BACKUP.$cip, 0777))     error(WRITE_PERMISSINS_NEEDED_TEXT.DIR_FS_BACKUP.$cip);
        recursive_mkdir(dirname(DIR_FS_BACKUP.$cip.'/'.$filepath).'/');
        if(@!copy(DIR_FS_CATALOG.$filepath, DIR_FS_BACKUP.$cip.'/'.$filepath)){
            error(COULDNT_COPY_TO_TEXT. $filepath."<br>to ".DIR_FS_BACKUP.$cip.'/'.$filepath);
        }
    } else {
        error(COULDNT_COPY_TO_TEXT. $filepath."<br>to ".DIR_FS_BACKUP.$cip.'/'.$filepath);

    }
}

function restore_backuped_file($filepath){
    global $contrib;
    ($contrib) ? $cip=$contrib: $cip=$_GET['contrib'];
    if ($cip && $filepath && is_file(DIR_FS_BACKUP.$cip.'/'.$filepath)) {
        if(@!copy(DIR_FS_BACKUP.$cip.'/'.$filepath, DIR_FS_CATALOG.$filepath)) {
            error(COULDNT_COPY_TO_TEXT. $filepath."<br> to:".DIR_FS_CATALOG.$filepath);
        }
    }
}

//Recived an array and returns filenames
function collect_all_filenames($t_array) {
    $files=array();
    if($t_array[0]) {
        foreach ($t_array as $name)     if ($name['FILE'][0]['@']['NAME'])    $files[]=$name['FILE'][0]['@']['NAME'];
    }
    return $files;
}

?>